<?php
class MessagesController extends AppController {

	var $name = 'Messages';
		
    var $paginate = array(
        'Message' => array(
	        'limit' => 10,
	        'order' => array(
	            'Message.added' => 'desc',
    			'Message.user_id' => 'asc'
	        ))
    );
    
	var $permissions = array(
		'add' => array('admin','manag','emplo','copyr','users'),
		'index' => array('admin','manag','emplo','copyr','users'),
		'view' => array('admin','manag','emplo','copyr','users'),
		'edit' => array('admin','manag','emplo','copyr','users'),
		'delete' => array('admin','manag','emplo','copyr','users'),
		'find' => array('admin','manag','emplo','copyr','users')
	);    
    
    var $statusy = array( );
    
	function beforeFilter(){
		parent::beforeFilter();
		$this->statusy = array(			
			1=>__("Inbox",true),
			2=>__("Outbox",true),
			3=>__("Archives",true),
			41=>__("Deleted",true),
			42=>__("Deleted",true),
			5=>__("Search",true)
		);
	}
	
	public $presetVars = array(
		array('field' => 'searchtext', 'type' => 'like'),
		array('field' => 'user_id', 'type' => 'value')
	);	
	
	public function find() {
		$this->paginate = null;
		
		$this->Prg->commonProcess();
		$this->paginate['conditions'] = $this->Message->parseCriteria($this->passedArgs);	
		$messages = $this->paginate();
		
		$this->set(compact('messages'));
		$this->set('status', '5');
		$this->set('statusy', $this->statusy);		
		$this->autoRender = false;
		$this->render('index');
	}	
	    
	function index($status = '1') {
		$status = ($status == 4) ? array(41,42,43) : $status;
		$this->Message->recursive = 0;
		$messages = $this->paginate('Message',array('Message.user_id'=>$this->Session->read("Auth.User.id"),'Message.status'=>$status));
		$this->set('messages', $messages);
		$this->set('status', $status);
		$this->set('statusy', $this->statusy);
		$this->set('user_id',$this->Session->read("Auth.User.id"));
		
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid message', true));
			$this->redirect(array('action' => 'index'));
		}

		$message = $this->Message->read(null, $id);
		$users_nadawca = $this->Message->User->read(null,$message['Message']['user_id']);
		$users_odbiorca = $this->Message->User->read(null,$message['Message']['fromto_user_id']);
		
		$users[$users_nadawca['User']['id']]['group'] = $users_nadawca['User']['group'];
		$users[$users_nadawca['User']['id']]['email'] = $users_nadawca['User']['email'];
		$users[$users_nadawca['User']['id']]['name'] = $users_nadawca['User']['first_name'].' '.$users_nadawca['User']['last_name'];
		$users[$users_odbiorca['User']['id']]['group'] = $users_odbiorca['User']['group'];
		$users[$users_odbiorca['User']['id']]['email'] = $users_odbiorca['User']['email'];
		$users[$users_odbiorca['User']['id']]['name'] = $users_odbiorca['User']['first_name'].' '.$users_odbiorca['User']['last_name'];
		
		$this->set(compact('users'));
				
		if($message['Message']['status'] == 1 ){
			$message['Message']['status'] = 3; /*przeczyatna*/
			if ($this->Message->save($message)){
				$this->Session->setFlash(__('The message has moved to Archives', true));
			}
		}
		$this->set('message', $message);
		$this->set('user_id',$this->Session->read("Auth.User.id"));
	}

	function add($odbiorca=null) {
		$users = $this->_users($odbiorca);
		
				
		if (!empty($this->data)) {
			$users = $this->_users('all');
			foreach ($this->data['Message']['user_id'] as $odbiorca => $value_user_id) {
				if(!empty($value_user_id)){
					$this->data['Message']['added'] = date('Y-m-d H:i:s');
					$this->data['Message']['user_id'] = $odbiorca;
					$name = (isset($users[$this->Session->read("Auth.User.id")]['name'])) ? $users[$this->Session->read("Auth.User.id")]['name'] : '';
					$this->data['Message']['fromto'] = $name;
					$this->data['Message']['fromto_user_id'] = $this->Session->read("Auth.User.id");
					$this->data['Message']['status'] = 1 /*new*/;
					$this->Message->create();
					if ($this->Message->save($this->data)){
						$user_odbiorca = $this->Message->User->read(null,$odbiorca);
						$to = $user_odbiorca['User']['email'];
						$from = $this->Message->User->field('email',array('id'=>$this->Session->read("Auth.User.id")));
						$subject = __('Have message on Vindcharter',true);
						$this->set('nadawca',$name);
						$this->_send($to, $from, $subject);
						
						$this->data['Message']['added'] = date('Y-m-d H:i:s');
						$this->data['Message']['fromto'] = $user_odbiorca['User']['first_name'].' '.$user_odbiorca['User']['last_name'];
						$this->data['Message']['fromto_user_id'] = $odbiorca;
						$this->data['Message']['status'] = 2 /*wyslane*/;
						$this->data['Message']['user_id'] = $this->Session->read("Auth.User.id"); //musi byc zdeklarowane po nadaniu fromto
						$this->Message->create();
						if (!$this->Message->save($this->data)){	
							$this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true));
						}
						
	
					} else {
						$this->Session->setFlash(__('The message could not be saved. Please, try again.', true));
					}
				}
			}
			$this->redirect(array('action' => 'index'));
		}
		// dodaj dla wybranego uzytkownika
		if(!is_null($odbiorca)){
			$this->data['Message']['user_id'][$odbiorca] = $odbiorca;
			$this->data['Message']['users'] = $users[$odbiorca]['name'].';';			
		}
		$user_id = $this->Session->read("Auth.User.id");
		$this->set(compact('users','user_id'));
	}
	
	private function _users($user_id){
		
		$filter = array();
		if($this->Session->read("Auth.User.group") == 'admin') $filter = array('admin','manag','emplo','users','copyr');
		if($this->Session->read("Auth.User.group") == 'manag') $filter = array('admin','manag','emplo','users','copyr');
		if($this->Session->read("Auth.User.group") == 'emplo') $filter = array('admin','manag','emplo','users');
		if($this->Session->read("Auth.User.group") == 'users') $filter = array('users');
		if($this->Session->read("Auth.User.group") == 'copyr') $filter = array('admin','manag','copyr','firms','users');

		$joins = array();
		array_push($joins, array('table' => 'friends', 'alias' => 'Friend', 'type' => 'INNER', 'conditions' => array( 'Friend.id = User.id')));
		// FRIENDS
		if($user_id == 'all'){
			$users_ = $this->Message->User->find('all',array('conditions'=>array('User.group'=>$filter),'order'=>'User.group'));
		}else{
			$users_ = $this->Message->User->find('all',array('conditions'=>array('User.group'=>$filter,'Friend.user_id'=>$this->Session->read("Auth.User.id")),'order'=>'User.group','joins'=>$joins));
		}
		$users = array();

		foreach ($users_ as $key => $u) {
			$users[$u['User']['id']]['group'] = $u['User']['group'];
			$users[$u['User']['id']]['email'] = $u['User']['email'];
			$users[$u['User']['id']]['name'] = $u['User']['first_name'].' '.$u['User']['last_name'];
		}
		if(!array_key_exists($this->Session->read("Auth.User.id"), $users)){
			// dane zalogowanego
			
			$user = $this->Message->User->read(null,$this->Session->read("Auth.User.id"));
			
// 			$users[$this->Session->read("Auth.User.id")] = $user[$type]['0'];
			$users[$this->Session->read("Auth.User.id")]['group'] = $user['User']['group'];
			$users[$this->Session->read("Auth.User.id")]['email'] = $user['User']['email'];
			$users[$this->Session->read("Auth.User.id")]['name'] = $user['User']['first_name'].' '.$user['User']['last_name'];
		}
		
		if(!array_key_exists($user_id, $users) && !empty($user_id) && $user_id != 'all'){
			// dane odbiorcy
				
			$odbiorca = $this->Message->User->read(null,$user_id);
				
// 			$users[$user_id] = $user[$type]['0'];
			$users[$user_id]['group'] = $odbiorca['User']['group'];
			$users[$user_id]['email'] = $odbiorca['User']['email'];
			$users[$user_id]['name'] = $odbiorca['User']['first_name'].' '.$odbiorca['User']['last_name'];
		}
		
// 		debug($users); die;
		return $users;
	} 
	
	private function _send($to,$from,$subject){
		if(Configure::read('Config.emails.debug'))
			//$this->Email->delivery = 'debug';
		
		
	    $this->Email->to = $to; 
        $this->Email->subject = $subject; 
//         $this->Email->replyTo = $from; 
        $this->Email->from = __("Vindcharter Message",true)."<{$from}>"; 
        $this->Email->template = 'have_message';
        $this->Email->sendAs = 'both';
        
         if ( $this->Email->send() ) { 
            $this->Session->setFlash(__('The message has been send', true)); 
        } else { 
            $this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true)); 
        }
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid message', true));
			$this->redirect(array('action' => 'index'));
		}
		$message = $this->Message->read(null, $id);
		$users = $this->_users($this->Session->read("Auth.User.id"));
		
		$this->set(compact('users'));
		
		if (!empty($this->data)) {
			
			foreach ($this->data['Message']['user_id'] as $user_id => $value_user_id) {
				if($value_user_id == $user_id ){
					$this->data['Message']['added'] = date('Y-m-d H:i:s');
					$this->data['Message']['user_id'] = $user_id;
					$this->data['Message']['fromto'] = $users[$this->Session->read("Auth.User.id")]['name'];
					$this->data['Message']['fromto_user_id'] = $this->Session->read("Auth.User.id");
					$this->data['Message']['status'] = 1 /*new*/;
					$this->Message->create();
					if ($this->Message->save($this->data)){
						
						$to = $this->Message->User->field('email',array('id'=> $user_id ));
						$from = $this->Message->User->field('email',array('id'=>$this->Session->read("Auth.User.id")));
						$subject = $this->data['Message']['name'];
						$content = $this->data['Message']['content'];
						$this->_send($to, $from, $subject, $content);
						
						$this->data['Message']['added'] = date('Y-m-d H:i:s');
						$this->data['Message']['fromto'] = $users[$this->data['Message']['user_id']]['name'];
						$this->data['Message']['fromto_user_id'] = $user_id;
						$this->data['Message']['status'] = 2 /*wyslane*/;
						$this->data['Message']['user_id'] = $this->Session->read("Auth.User.id"); //musi byc zdeklarowane po nadaniu fromto
						$this->Message->create();
						if (!$this->Message->save($this->data)){	
							$this->Session->setFlash(__('The message could not be saved to sendet box. Please, try again.', true));
						}
						
	
					} else {
						$this->Session->setFlash(__('The message could not be saved. Please, try again.', true));
					}
				}
			}			
		}			
		
		if (empty($this->data)) {
			$this->data = $message;
			$from_uId = $this->data['Message'][(($this->data['Message']['status']==1 || $this->data['Message']['status']==3 || $this->data['Message']['status']==41 || $this->data['Message']['status']== 43)?'fromto_':'').'user_id'];
			$this->data['Message']['user_id'] = $from_uId;

			$user = $this->Message->User->read(null,$from_uId );
			if(!empty($user)){
				$this->data['Message']['users'] = $user['User']['first_name'].' '.$user['User']['last_name'].';';	
			}else{
				$this->Session->setFlash(__('The message could not be edited. Please, try again.', true));
			}
		}

		$this->set('user_id',$this->Session->read("Auth.User.id"));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for message', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->data = $this->Message->read(null, $id);
		$status = $this->data['Message']['status'];
		if($status[0] == '4'){
			if ($this->Message->delete($id)) {
				$this->Session->setFlash(__('Message deleted', true));
				$this->redirect(array('action'=>'index',4));
			}			
		}else{
			// dodajemy 4 przed obecny status i tym samym zmieniamy wiadomosc na usunietą
			$this->data['Message']['status'] = '4'.$status;
			if ($this->Message->save($this->data)) {
				$this->Session->setFlash(__('Message deleted', true));
				$this->redirect(array('action'=>'index',$status));
			}
		}
		$this->Session->setFlash(__('Message was not deleted', true));
		$this->redirect(array('action' => 'index',$status));
	}
}
?>